#!/bin/bash

APP_NAME="deepseek-chat"
PID_FILE="server.pid"
LOG_FILE="server.log"

get_pid() {
    if [ -f "$PID_FILE" ]; then
        cat "$PID_FILE"
    else
        echo ""
    fi
}

start() {
    pid=$(get_pid)
    if [ -n "$pid" ]; then
        if ps -p "$pid" > /dev/null; then
            echo "$APP_NAME is already running (PID: $pid)"
            return
        fi
    fi

    PORT=${2:-8866} # Default to 8866 if not provided
    DB_PATH=${3:-"/home/data/chat.db"} # Default to data/chat.db if not provided

    echo "Starting $APP_NAME on port $PORT with DB at $DB_PATH..."
    
    # Export env vars for the application
    export PORT=$PORT
    export DB_PATH=$DB_PATH
    
    nohup ./$APP_NAME > "$LOG_FILE" 2>&1 &
    new_pid=$!
    echo "$new_pid" > "$PID_FILE"
    echo "$APP_NAME started (PID: $new_pid). Logs: $LOG_FILE"
}

stop() {
    pid=$(get_pid)
    if [ -n "$pid" ]; then
        if ps -p "$pid" > /dev/null; then
            echo "Stopping $APP_NAME (PID: $pid)..."
            kill "$pid"
            rm "$PID_FILE"
            echo "$APP_NAME stopped."
        else
            echo "$APP_NAME is not running (stale PID file removed)."
            rm "$PID_FILE"
        fi
    else
        echo "$APP_NAME is not running."
    fi
}

status() {
    pid=$(get_pid)
    if [ -n "$pid" ]; then
        if ps -p "$pid" > /dev/null; then
            echo "$APP_NAME is running (PID: $pid)"
        else
            echo "$APP_NAME is not running (stale PID file)."
        fi
    else
        echo "$APP_NAME is not running."
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 1
        start "$1" "$2" "$3"
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start [port] [db_path]|stop|restart [port] [db_path]|status}"
        exit 1
        ;;
esac
